/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package top.fsb.dataview.service.controller;

import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import top.fsb.dataview.service.annotation.ApiLog;
import top.fsb.dataview.service.constant.AppConstant;
import top.fsb.dataview.service.constant.TokenConstant;
import top.fsb.dataview.service.info.Kv;
import top.fsb.dataview.service.info.TokenInfo;
import top.fsb.dataview.service.utils.RedisUtil;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.*;

/**
 * 模拟登录接口以便快速获取token，正式使用请对接BladeX的blade-auth服务
 *
 * @author Chill
 */
@ApiIgnore
@ApiSort(1)
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_AUTH_NAME)
@Api(value = "用户授权认证", tags = "授权接口")
public class AuthController {

	@Resource
	private  RedisUtil redisUtil;

	private final static String CAPTCHA_KEY = "blade:auth::blade:captcha:";

	@ApiLog("登录用户验证")
	@PostMapping("/oauth/token")
	@ApiOperation(value = "获取认证令牌", notes = "传入租户ID:tenantId,账号:account,密码:password")
	public Kv token(@ApiParam(value = "租户ID", required = true) @RequestParam String tenantId,
					@ApiParam(value = "账号", required = true) @RequestParam(required = false) String username,
					@ApiParam(value = "密码", required = true) @RequestParam(required = false) String password) {
		// 创建授权类
		Kv authInfo = Kv.create();

		//设置jwt参数
		Map<String, Object> param = new HashMap<>(16);
		param.put(TokenConstant.TOKEN_TYPE, TokenConstant.ACCESS_TOKEN);
		param.put(TokenConstant.TENANT_ID, "000000");
		param.put(TokenConstant.USER_ID, "1123598821738675201");
		param.put(TokenConstant.DEPT_ID, "1123598813738675201");
		param.put(TokenConstant.POST_ID, "1123598817738675201");
		param.put(TokenConstant.ROLE_ID, "1123598816738675201");
		param.put(TokenConstant.OAUTH_ID, "233");
		param.put(TokenConstant.ACCOUNT, "admin");
		param.put(TokenConstant.USER_NAME, "admin");
		param.put(TokenConstant.NICK_NAME, "admin");
		param.put(TokenConstant.ROLE_NAME, "admin");
		param.put(TokenConstant.DETAIL, "admin");

		//拼装accessToken
		TokenInfo accessToken = createJWT(param, "audience", "issuser", TokenConstant.ACCESS_TOKEN);
		//返回accessToken
		return authInfo.set(TokenConstant.TENANT_ID, "000000")
			.set(TokenConstant.USER_ID, "1123598821738675201")
			.set(TokenConstant.DEPT_ID, "1123598813738675201")
			.set(TokenConstant.POST_ID, "1123598817738675201")
			.set(TokenConstant.ROLE_ID, "1123598816738675201")
			.set(TokenConstant.OAUTH_ID, "233")
			.set(TokenConstant.ACCOUNT, "admin")
			.set(TokenConstant.USER_NAME, "admin")
			.set(TokenConstant.NICK_NAME, "admin")
			.set(TokenConstant.ROLE_NAME, "admin")
			.set(TokenConstant.AVATAR, "")
			.set(TokenConstant.ACCESS_TOKEN, accessToken.getToken())
			.set(TokenConstant.REFRESH_TOKEN, accessToken.getToken())
			.set(TokenConstant.TOKEN_TYPE, TokenConstant.BEARER)
			.set(TokenConstant.EXPIRES_IN, accessToken.getExpire())
			.set(TokenConstant.DETAIL, "admin")
			.set(TokenConstant.LICENSE, TokenConstant.LICENSE_NAME);
	}

	@GetMapping("/oauth/logout")
	@ApiOperation(value = "退出登录")
	public Kv logout() {
		return Kv.create().set("success", "true").set("msg", "success");
	}

	@GetMapping("/oauth/captcha")
	@ApiOperation(value = "获取验证码")
	public Kv captcha() {
		SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
		String verCode = specCaptcha.text().toLowerCase();
		String key = UUID.randomUUID().toString();
		// 存入redis并设置过期时间为30分钟
		redisUtil.setEx(CAPTCHA_KEY + key, verCode, Duration.ofMinutes(30));
		// 将key和base64返回给前端
		return Kv.create().set("key", key).set("image", specCaptcha.toBase64());
	}

	private TokenInfo createJWT(Map<String, Object> user, String audience, String issuer, String tokenType) {
		TokenInfo tokenInfo = new TokenInfo();
		tokenInfo.setToken(user.toString());
		tokenInfo.setExpire(3600);
		if ( "access_token".equals(tokenType)) {
			String tenantId = String.valueOf(user.get("tenant_id"));
			String userId = String.valueOf(user.get("user_id"));
//			JwtUtil.addAccessToken(tenantId, userId, tokenInfo.getToken(), tokenInfo.getExpire());
		}
			return tokenInfo;
	}



}
